<?php

	namespace app\common\model\goods\record;

	use app\common\model\User;
	use think\Cache;
	use think\Log;
	use think\Model;
	use think\Queue;

	class Ohcard extends Model{

		// 表名
		protected $name = 'ohcard_record';
		// 自动写入时间戳字段
		protected $autoWriteTimestamp = 'int';
		// 定义时间戳字段名
		protected $createTime = 'createtime';
		protected $updateTime = null;

		protected static $cache_prefix = 'user_ohcard_balance_',$cache_time = 1800;
		protected static $cache_prefix_freetimes = 'user_ohcard_freetimes_';

		/**
		 * 结算
		 * @param $order
		 * @return void
		 */
		public static function settle($user_id,$amount){
			return self::change($user_id, $amount, '充值');
		}

		/**
		 * 更新数据
		 * @param $user_id
		 * @param $amount
		 * @param $memo
		 * @return void
		 */
		public static function change($user_id, $amount, $memo = '', $message = ''){
			$amount = $amount * 24 * 3600;

			$before = self::getBalance($user_id);
			$after = self::getAfter($before, $amount);
			$cache_prefix = self::$cache_prefix;
			$type = 'ohcard_balance';

			// 更新缓存
			if(self::setCache($user_id, $after, $cache_prefix)){
				// 更新数据库操作放入队列
				Queue::push('Product@ohcard', ['user_id' => $user_id, 'amount' => $amount, 'before' => $before, 'memo' => $memo, 'message' => $message, 'type' => $type]);
				return true;
			}else{
				return false;
			}
		}

		/**
		 * 记录日志
		 * @param $user_id
		 * @param $amount
		 * @param $before
		 * @param $memo
		 * @return void
		 * @throws \think\exception\PDOException
		 */
		public static function log($data, $job_id){
			Log::write($data, 'debug');
			Log::write('$job_id:'.$job_id, 'debug');
			self::startTrans();
			try {
				if ($data['amount'] != 0) {
//					$user = User::lock(true)->where('id', $data['user_id'])->find();
					$user = User::where('id', $data['user_id'])->find();

					if($data['type'] == 'ohcard_balance'){
						// 是否已经写入
						$isset = self::where(['job_id' => $job_id, 'user_id' => $data['user_id']])->count();
						Log::write('$isset:'.$isset, 'debug');
						if($isset <= 0){
							$after = self::getAfter($data['before'], $data['amount']);
							Log::write('$after:'.$after, 'debug');
							//更新会员信息
							$save = User::where('id', $data['user_id'])->update(['ohcard_balance' => $after]);
							Log::write('$save:'.$save, 'debug');
							//写入日志
							$create = self::create([
								'user_id' => $data['user_id'],
								'ohcard' => $data['amount'],
								'before' => $data['before'],
								'after' => $after,
								'memo' => $data['memo'],
								'message' => $data['message'],
								'job_id' => $job_id,
							]);
							Log::write('$create:'.$create, 'debug');
						}
					}elseif($data['type'] == 'free_times'){
						$user->free_times -= 1;
						$user->save();
					}
				}else{
					Log::write('amount==0:'.$data['amount'], 'debug');
				}
				self::commit();
				Log::write('commit', 'debug');
				return true;
			} catch (\Exception $e) {
				Log::write($e->getMessage().' in '.$e->getFile().' '.$e->getLine(),'debug');
				self::rollback();
				return false;
			}
		}

		/**
		 * 获取当前余额
		 * @param $user_id
		 * @return float|mixed|string
		 */
		public static function getBalance($user_id){
			$redis = Cache::store('redis');
			$ohcard = $redis->get(self::$cache_prefix.$user_id, null);
			if(!$ohcard){
//				$ohcard = User::lock(true)->where('id','=',$user_id)->value('ohcard_balance');
				$ohcard = User::where('id','=',$user_id)->value('ohcard_balance');
				$ohcard = $ohcard <= time() ? time() : $ohcard;
				self::setCache($user_id, $ohcard);
			}
			return $ohcard;
		}

		public static function setCache($user_id, $amount, $prefix = ''){
			$prefix = $prefix ?: self::$cache_prefix;
			return Cache::store('redis')->set($prefix.$user_id, (int)$amount, self::$cache_time);
		}

		public static function getAfter($before, $amount){
			return $before + $amount;
		}
	}